<template>
  <div>
    <div class="request" v-if="!addShow && !dtlShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-hasPermi="['system:inorderAudit:query']"
          class="btn search"
          @click="getList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="warehousingApplyCode">入库编号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicantDateStr">申请日期</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicantName">申请人</el-checkbox>
            </div>
            <div>
              <el-checkbox label="deptName">申请部门</el-checkbox>
            </div>
            <div>
              <el-checkbox label="warehousingApplyTypeName"
                >入库类型</el-checkbox
              >
            </div>
            <div>
              <el-checkbox label="contractCode">关联合同</el-checkbox>
            </div>
            <div>
              <el-checkbox label="projectName">关联项目</el-checkbox>
            </div>
            <div>
              <el-checkbox label="checkStatusName">审核状态</el-checkbox>
            </div>
            <div>
              <el-checkbox label="nextNodeName">下步流程</el-checkbox>
            </div>
            <div>
              <el-checkbox label="inStatusName">入库状态</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item" style="margin-bottom: 10px">
          <el-input
            clearable
            v-model="params.warehousingApplyCode"
            class="search-input"
            placeholder="请输入入库编号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.applicantName"
            class="search-input"
            placeholder="请输入申请人"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.contractCode"
            class="search-input"
            placeholder="请输入合同编号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.projectName"
            class="search-input"
            placeholder="请输入项目名称"
          ></el-input>
        </div>

        <div class="search-item">
          <el-select
            v-model="params.warehousingApplyType"
            placeholder="请选择入库类型"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in inStatusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>

        <div class="search-item">
          <el-select
            v-model="params.checkStatus"
            placeholder="请选择审核状态"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in auditStatusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>

        <div class="search-item">
          <el-select
            v-model="params.inStatus"
            placeholder="请选择入库状态"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in inorderStatusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
      </div>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="list"
        border
        height="59.2vh"
        :header-cell-style="{ 'text-align': 'center' }"
        @sort-change="sortChange"
      >
        <el-table-column label="操作" min-width="150px">
          <template #default="{ row }">
            <div class="table-operate">
              <!--审核流程 -->
              <el-icon
                v-if="[1, 2].includes(row.checkStatus) && row.auditStatus == 1"
                v-hasPermi="['system:inorder:list']"
                title="审核"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('audit', row)"
              >
                <Checked />
              </el-icon>

              <el-icon
                v-if="row.checkStatus == 3 && row.inStatus == 0"
                v-hasPermi="['system:inorderAudit:check']"
                title="入库"
                color="#0000FF"
                class="table-icon"
                :size="20"
                @click="handleOperate('check', row)"
              >
                <img
                  src="@/assets/icons/images/warehousing.png"
                  style="width: 16px; height: 18px"
                />
              </el-icon>

              <el-icon
                v-hasPermi="['system:inorderAudit:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>

              <el-icon
                v-hasPermi="['system:inorderAudit:delete']"
                title="删除"
                v-if="[5].includes(row.checkStatus) && false"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
            </div> </template
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="80"
          align="center"
        />
        <el-table-column
          label="入库编号"
          prop="warehousingApplyCode"
          v-if="checkList.includes('warehousingApplyCode')"
          :show-overflow-tooltip="true"
          min-width="150"
          sortable="custom"
        />
        <el-table-column
          label="申请日期"
          prop="applicantDateStr"
          v-if="checkList.includes('applicantDateStr')"
          :show-overflow-tooltip="true"
          min-width="150"
          sortable="custom"
        />
        <!--:formatter="dateFormat"-->
        <el-table-column
          label="申请人"
          prop="applicantName"
          v-if="checkList.includes('applicantName')"
          :show-overflow-tooltip="true"
          min-width="130"
          sortable="custom"
        />
        <el-table-column
          label="申请部门"
          prop="deptName"
          v-if="checkList.includes('deptName')"
          :show-overflow-tooltip="true"
          min-width="130"
          sortable="custom"
        />
        <el-table-column
          label="入库类型"
          prop="warehousingApplyTypeName"
          v-if="checkList.includes('warehousingApplyTypeName')"
          :show-overflow-tooltip="true"
          min-width="130"
          sortable="custom"
        />
        <el-table-column
          label="关联合同"
          prop="contractCode"
          v-if="checkList.includes('contractCode')"
          :show-overflow-tooltip="true"
          min-width="180"
          sortable="custom"
        >
          <template #default="{ row }">
            <span
              v-if="row.purchaseContractId"
              @click="handleContractCodeDetail(row)"
              style="color: #409eff; cursor: pointer"
              >{{ row.contractCode }}</span
            >
            <span v-else>{{ row.contractCode }}</span>
          </template></el-table-column
        >
        <el-table-column
          label="关联项目"
          prop="projectName"
          v-if="checkList.includes('projectName')"
          :show-overflow-tooltip="true"
          width="180"
          sortable="custom"
        >
          <template #default="{ row }">
            <span
              v-if="row.projectId"
              @click="handleProjectDetail(row)"
              style="color: #409eff; cursor: pointer"
              >{{ row.projectCode }}</span
            >
            <span v-else>{{ row.projectCode }}</span>
          </template></el-table-column
        >
        <el-table-column
          label="审核状态"
          prop="checkStatusName"
          v-if="checkList.includes('checkStatusName')"
          :show-overflow-tooltip="true"
          min-width="130"
          sortable="custom"
        >
          <template #default="{ row }">
            <span :style="getStatusColor(row.checkStatusName)">{{
              row.checkStatusName
            }}</span>
          </template></el-table-column
        >
        <el-table-column
          label="下步流程"
          prop="nextNodeName"
          v-if="checkList.includes('nextNodeName')"
          :show-overflow-tooltip="true"
          min-width="150"
          sortable="custom"
        />
        <el-table-column
          label="入库状态"
          prop="inStatusName"
          v-if="checkList.includes('inStatusName')"
          :show-overflow-tooltip="true"
          min-width="130"
          sortable="custom"
        />
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getList"
      />
    </div>

    <InorderAdd
      ref="inorderAddRef"
      v-if="addShow"
      v-model:addShow="addShow"
      @refreshList="getList"
      :pageType="pageType"
    />

    <InorderDtl
      ref="inorderDtlRef"
      v-if="dtlShow"
      v-model:dtlShow="dtlShow"
      @refreshList="getList"
      :pageType="pageType"
    />
  </div>
</template>

<script setup>
import InorderAdd from './add.vue'
import InorderDtl from './dtl.vue'
import { getDictsApi } from '@/api/dict'
import { getInorderListApi, deleteOrder } from '@/api/stock/inorder'
import { useMouseInElement } from '@vueuse/core'
import { addTableHeaderApi, getTableHeaderApi } from '@/api/pub'
import { ElMessage, ElMessageBox } from 'element-plus'
// 路由
const route = useRoute()
// 搜索参数
const params = reactive({
  warehousingApplyCode: null,
  applicantName: null,
  contractCode: null,
  projectName: null,
  warehousingApplyType: null,
  checkStatus: null,
  inStatus: null,
  type: 2,
  pageNum: 1,
  pageSize: 50,
  sortField:"",
  sortOrder:"",
})
const router = useRouter()
// 表格加载效果
const loading = ref(false)
// 数据list列表
const list = ref([])
// 审核状态
const inStatusList = ref([])
// 审核状态
const auditStatusList = ref([])

const inorderStatusList = ref([])
// 总数
const total = ref(0)
// 客户新增组件引用
const inorderAddRef = ref(null)
// 客户新增组件显隐
const addShow = ref(false)
// 操作类型
const pageType = ref('')

const inorderDtlRef = ref(null)

const dtlShow = ref(false)

const checkList = ref([
  'warehousingApplyCode',
  'applicantDateStr',
  'applicantName',
  'deptName',
  'warehousingApplyTypeName',
  'contractCode',
  'projectName',
  'checkStatusName',
  'nextNodeName',
  'inStatusName',
])

/**
 * @description: 复选框选中
 */
const handleCheckChange = async (val) => {
  var str = val.join(',')
  const result = await addTableHeaderApi({
    moduleType: 27,
    titleField: str,
  })
}

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: 27,
  })
  if (result.code == 200) {
    var arr = result.data.titleField.split(',')
    checkList.value = arr
  }
}

/**
 * @description: 重置
 */
const handleRefresh = () => {
  Object.assign(params, {
    warehousingApplyCode: null,
    applicantName: null,
    contractCode: null,
    projectName: null,
    warehousingApplyType: null,
    checkStatus: null,
    inStatus: null,
    type: 2,
    pageNum: 1,
    pageSize: 50,
    sortField:"",
    sortOrder:"",
  })
  getList()
}

/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
 const sortChange = (column) => {
  params.sortField = column.prop;
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else {
    params.sortOrder = "ASC"; // 排序或倒序
  }
  getList();
};

/**
 * @description: 获取客户列表
 */
const getList = async () => {
  try {
    loading.value = true
    let { pageNum, pageSize } = params
    const res = await getInorderListApi({ pageNum, pageSize }, params)
    list.value = res.rows
    total.value = res.total
    loading.value = false
  } catch {
    loading.value = false
  }
}
/*dateFormat:function(row,column){
  var date = row[column.property];
  if(date == undefined){
    return "";
  }
  return useMouseInElement(date).format("YYYY-MM-DD")
}*/

const showAdd = async (type) => {
  pageType.value = type
  addShow.value = true

  nextTick(() => {
    inorderAddRef.value.showAdd()
  })
}

/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case 'audit':
      pageType.value = type
      addShow.value = true

      nextTick(() => {
        inorderAddRef.value.showEdit(row)
      })
      break
    case 'check':
      pageType.value = type
      addShow.value = true

      nextTick(() => {
        inorderAddRef.value.showEdit(row)
      })
      break
    case 'detail':
      pageType.value = type
      dtlShow.value = true
      nextTick(() => {
        inorderDtlRef.value.showEdit(row)
      })
      break

    case 'delete':
      ElMessageBox.confirm('此操作将删除该入库信息，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtnClass',
        cancelButtonClass: 'cancelBtnClass',
        type: 'warning',
      })
        .then(async () => {
          const res = await deleteOrder(row.id)
          if (res.code === 200) {
            ElMessage.success(res.msg)
            getList()
          } else {
            ElMessage.error(res.msg)
          }
        })
        .catch(() => {})
      break

    default:
      break
  }
}
/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum
  const pageSize = params.pageSize
  const truelndex = (currentPage - 1) * pageSize + index + 1
  return truelndex
}
/**
 * @description: 获取字典
 */
async function getDicts() {
  // 入库类型
  await getDictsApi('erp_warehousing_apply_type').then((res) => {
    if (res.code === 200) {
      inStatusList.value = res.data
    }
  })

  // 审核状态
  await getDictsApi('erp_warehousing_check_status').then((res) => {
    if (res.code === 200) {
      auditStatusList.value = res.data.filter((status) => status.value !== 0)
    }
  })

  // 入库状态
  await getDictsApi('erp_warehousing_apply_instatus').then((res) => {
    if (res.code === 200) {
      inorderStatusList.value = res.data
    }
  })
}
/* 跳转项目详情 */
const handleProjectDetail = (row) => {
  const { href } = router.resolve({
    path: `/sales/project`,
    query: { projectId: row.projectId },
  })
  window.open(href, '_blank')
  // window.open(`/sales/project?projectId=${row.projectId}`, "_blank");
}

/* 跳转合同详情 */
const handleContractCodeDetail = (row) => {
  const { href } = router.resolve({
    path: `/SealManage/contractSeal`,
    query: { purchaseContractId: row.purchaseContractId },
  })
  window.open(href, '_blank')
  // window.open(
  //   `/purchase/contractSeal?purchaseContractId=${row.purchaseContractId}`,
  //   "_blank"
  // );
}
onMounted(() => {
  // 路由携带项目id参数，直接显示详情页

  if (route.query?.applyId) {
    let applyId = route.query.applyId
    pageType.value = 'detail'
    dtlShow.value = true
    nextTick(() => {
      inorderDtlRef.value.showEdit({
        id: applyId,
        checkStatus: 3,
      })
    })
  }
  if (route.query?.businessId) {
    let applyId = route.query.businessId
    pageType.value = 'audit'
    addShow.value = true
    nextTick(() => {
      inorderAddRef.value.showEdit({
        id: Number(applyId),
        checkStatus: 1,
      })
    })
  }
  if (route.query?.myinfoId) {
    let applyId = route.query.myinfoId
    pageType.value = 'detail'
    dtlShow.value = true
    nextTick(() => {
      inorderDtlRef.value.showEdit({
        id: Number(applyId),
        checkStatus: 3,
      })
    })
  }
  getDicts()
  getList()
  getTableHeader()
})
</script>
<style>
@import '@/assets/styles/confirmBtn.css';
</style>
<style lang="scss" scoped>
.request {
  padding: 20px;
  width: 100%;
  height: 100%;
  .pagination {
    margin-top: 20px;
  }
  .search {
    flex-wrap: wrap;
  }
}
</style>
